// 封装axios公共函数


import axios from "axios";
// 引入store仓库
import store from "@/store";
// 引入MSG
import { Message } from "element-ui";



// 封装公共地址，超时时间
const instance = axios.create({
    baseURL: 'http://sell.h5.itsource.cn:8087',
    timeout: 10000
})

// 封装请求拦截器
instance.interceptors.request.use(
    // config信息请求对象
    config => {
        // 获取token
        const token = store.getters.token
        token && (config.headers.authorization = token)
        return config
    },
    // 抛出错误信息
    err => {
        return Promise.reject(err)
    }
)

// 封装响应拦截器
instance.interceptors.response.use(
    response => {
        // 抛出请求成功的错误信息
        let { code, msg } = response.data
        if (code === 0) {
            Message.success(msg)
        }
        else if (code === 1) {
            Message.error(msg)
        }
        else if (code === 5001) {
            Message.warning(msg)
        }
        return response
    },
    err => {
        // 抛出请求链接失败的错误信息
        let { response, message } = err
        if (response) {
            switch (response.status) {
                case 401:
                    Message.error(message)
                    break;
                case 403:
                    Message.error(message)
                    break;
                case 404:
                    Message.error(message)
                    break;
                case 500:
                    Message.error(message)
                    break;
                default:
                    Message.error(message)
                    break;
            }
        } else {
            Message.error(message)
        }
        return Promise.reject(err)
    }
)

export default instance